/*
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-27 16:47:58
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-03-18 23:50:18
 * @FilePath: /ai-interview-vue/src/utils/audioManager.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * 音频管理类
 * 处理音频队列播放、暂停、恢复等功能
 */
class AudioManager {
    /**
     * 初始化音频管理器
     */
    constructor() {
        this.audio = new Audio()
        this.queue = []
        this.isPlaying = false
        this.setupEventListeners()
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        this.audio.addEventListener('ended', () => this.playNext())
        this.audio.addEventListener('error', (error) => {
            console.error('Audio playback error:', error)
            this.playNext()
        })
    }

    /**
     * 添加音频到播放队列
     * @param {string} url - 音频文件URL
     */
    addToQueue(url) {
        this.queue.push(url)
        // if (!this.isPlaying) {
        //     this.playNext()
        // }
    }

    /**
     * 播放下一个音频
     */
    playNext() {
        if (this.queue.length > 0) {
            const url = this.queue.shift()
            this.play(url)
        } else {
            this.isPlaying = false
        }
    }

    /**
     * 播放指定URL的音频
     * @param {string} url - 音频文件URL
     */
    play(url) {
        try {
            this.audio.src = url
            this.audio.play()
            this.isPlaying = true
        } catch (error) {
            console.error('Failed to play audio:', error)
            this.isPlaying = false
        }
    }

    /**
     * 停止音频播放
     */
    stop() {
        this.audio.pause()
        this.audio.currentTime = 0
        this.isPlaying = false
        this.queue = []
    }

    /**
     * 暂停音频播放
     */
    pause() {
        this.audio.pause()
        this.isPlaying = false
    }

    /**
     * 恢复音频播放
     */
    resume() {
        this.audio.play()
        this.isPlaying = true
    }
}

export default AudioManager 